package com.panopset.map;

import static com.panopset.Util.COLON;
import static com.panopset.Util.DOS_RTN;
import static com.panopset.Util.saveStringToFile;

import java.io.File;
import java.io.StringWriter;
import java.util.Collections;
import java.util.Map;
import java.util.TreeMap;

import com.panopset.flywheel.ReservedWords;

public class KeyReporter {
    public static final KeyReporter singleton = new KeyReporter();
    public boolean reportNumerics = false;


    private KeyReport getKeyReport(String source) {
        KeyReport rtn = keyReports.get(source);
        if (rtn == null) {
            rtn = new KeyReport();
            keyReports.put(source, rtn);
        }
        return rtn;
    }

    public void reportUsedKey(String source, String key) {
        KeyReport keyReport = getKeyReport(source);
        if (!keyReport.usedKeys.contains(key)) {
            keyReport.usedKeys.add(key);
        }
    }

    public void reportDefinedKey(String source, String key) {
        KeyReport keyReport = getKeyReport(source);
        if (!keyReport.dfndKeys.contains(key)) {
            keyReport.dfndKeys.add(key);
        }
    }

    public void reportUnusedKeys(String file) {
        StringWriter sw = new StringWriter();
        for (String source: keyReports.keySet()) {
            StringWriter hdr = new StringWriter();
            hdr.append("*********" + source + COLON);
            hdr.append(DOS_RTN);
            KeyReport keyReport = getKeyReport(source);
            for (String s : keyReport.usedKeys) {
                keyReport.dfndKeys.remove(s);
            }
            if (!reportNumerics) {
                for (int i = 0; i<100; i++) {
                    keyReport.dfndKeys.remove("" + i);
                }
            }
            keyReport.dfndKeys.remove(ReservedWords.FILE);
            keyReport.dfndKeys.remove(ReservedWords.DEPTH_CHARGE);
            keyReport.dfndKeys.remove(ReservedWords.SCRIPT);
            keyReport.dfndKeys.remove(ReservedWords.SPLITS);
            keyReport.dfndKeys.remove(ReservedWords.TARGET);
            keyReport.dfndKeys.remove(ReservedWords.TEMPLATE);
            keyReport.dfndKeys.remove(ReservedWords.TOKENS);
            boolean firstTime = true;
            for (String s : keyReport.dfndKeys) {
                if (firstTime) {
                    sw.append(hdr.toString());
                    firstTime = false;
                }
                sw.append(s);
                sw.append(DOS_RTN);
            }
        }
        saveStringToFile(sw.toString(), new File(file));
    }

    private final Map<String, KeyReport> keyReports = Collections.synchronizedSortedMap(new TreeMap<String, KeyReport>());

    private KeyReporter() {}
}
